import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import '../../api/api_auth_center.dart';
import '../../core/app_config.dart';
import '../../core/auth/user_manager.dart';
import '../../core/auth/user_profile.dart';
import '../../core/auth/user_session.dart';
import '../../core/crypto/sm2_utils.dart';
import '../../exception/global_error_handler.dart';
import '../../route/route_utils.dart';
import '../../route/routes.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool _rememberMe = false;

  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _obscurePassword = true;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadRememberedUser();
  }

  Future<void> _loadRememberedUser() async {
    final remembered = await RememberMeStorage().load();
    if (remembered != null) {
      setState(() {
        _usernameController.text = remembered.username;
        _passwordController.text = remembered.password;
        _rememberMe = true;
      });
    }
  }

  Future<void> _handleLogin() async {
    // 表单校验
    if (_usernameController.text.isEmpty || _passwordController.text.isEmpty) {
      showToast("用户名和密码不能为空");
      return;
    }

    setState(() => _isLoading = true);

    try {
      var username = _usernameController.text;
      var password = _passwordController.text;

      // 获取公钥并加密密码
      // var publicKeyResponse = await ApiAuthCenter.api.getPublicKey();
      // var encryptPwd = SM2Utils.encrypt(password, publicKeyResponse!.publicKey);

      var map = {
        "username": username,
        "password": password,
        "clientId": AuthCenterConfig.clientId,
      };

      // 登录成功，存储 token 等信息
      var authToken = await ApiAuthCenter.api.login(map);
      var session = UserSession(
        gsid: authToken!.gsid,
        accessToken: authToken.accessToken,
        refreshToken: authToken.refreshToken,
        expireAt:
        DateTime.now().add(Duration(seconds: authToken.expiresIn.toInt())),
      );

      await UserManager().saveSession(session);

      var authMe = authToken.user;
      var profile = UserProfile(
        id: authMe.userId,
        username: authMe.username,
        nickname: authMe.nickname,
        phone: authMe.phone,
        email: authMe.email,
        avatar: authMe.avatar,
      );
      await UserManager().updateProfile(profile);

      // 记住我
      if (_rememberMe) {
        await RememberMeStorage()
            .save(RememberMe(username: username, password: password));
      } else {
        await RememberMeStorage().clear();
      }

      // 登录成功后跳转首页并清空栈
      if (mounted) {
        RouteUtils.pushNamedAndRemoveUntil(context, RoutePath.home);
      }
    } catch (e) {
      // 这里可以直接 showToast 或者用全局错误提示
      GlobalErrorHandler().handleError(e);
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }


  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Card(
            margin: const EdgeInsets.symmetric(horizontal: 12),
            shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
            elevation: 2,
            child: Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // Logo
                  ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Image.asset(
                      'assets/images/app_logo.jpg',
                      width: 72,
                      height: 72,
                    ),
                  ),
                  const SizedBox(height: 16),
                  Text(l10n.loginWelcomeBack,
                      style: Theme.of(context).textTheme.titleLarge),
                  const SizedBox(height: 24),

                  _buildTextField(
                    label: l10n.loginUsername,
                    icon: Icons.email_outlined,
                    controller: _usernameController,
                  ),
                  const SizedBox(height: 16),
                  _buildTextField(
                    label: l10n.loginPassword,
                    icon: Icons.lock_outline,
                    controller: _passwordController,
                    isPassword: true,
                  ),
                  const SizedBox(height: 8),

                  // 记住我
                  Row(
                    children: [
                      Checkbox(
                        value: _rememberMe,
                        onChanged: (v) =>
                            setState(() => _rememberMe = v ?? false),
                      ),
                      Text(l10n.loginRememberMe),
                    ],
                  ),
                  const SizedBox(height: 12),

                  // 登录按钮
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: _isLoading ? null : _handleLogin,
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 14),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12)),
                      ),
                      child: _isLoading
                          ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                            strokeWidth: 2, color: Colors.white),
                      )
                          : Text(l10n.loginSignIn),
                    ),
                  ),
                  const SizedBox(height: 12),

                  // 注册 & 忘记密码
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      TextButton(
                        onPressed: () {
                          RouteUtils.pushForNamed(context, RoutePath.register);
                        },
                        child: Text(l10n.loginSignUp),
                      ),
                      TextButton(
                        onPressed: () {
                          RouteUtils.pushForNamed(
                              context, RoutePath.forgotPassword);
                        },
                        child: Text(l10n.loginForgotPassword),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTextField({
    required String label,
    required IconData icon,
    required TextEditingController controller,
    bool isPassword = false,
  }) {
    final color = Theme.of(context).colorScheme;
    return TextField(
      controller: controller,
      obscureText: isPassword && _obscurePassword,
      decoration: InputDecoration(
        labelText: label,
        prefixIcon: Icon(icon, color: color.onSurfaceVariant),
        suffixIcon: isPassword
            ? IconButton(
          icon: Icon(
            _obscurePassword ? Icons.visibility_off : Icons.visibility,
          ),
          onPressed: () =>
              setState(() => _obscurePassword = !_obscurePassword),
        )
            : null,
        filled: true,
        fillColor: color.surfaceContainerHighest.withOpacity(0.3),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
      ),
    );
  }
}
